﻿using System.Net;
using System.Net.Sockets;
using System.Web;
using System.Web.Mvc;
using EPiServer.Common;
using EPiServer.Common.Comments;
using JoelAbrahamsson.Web.ExtensionMethods;

namespace JoelAbrahamsson.Web.Common
{
    public class ProjectHoneyPotCommentValidator : ICommentValidator
    {
        private string _projectHoneyPotAccessKey;
        private string _projectHoneyPostDnsSuffix;

        public ProjectHoneyPotCommentValidator(string projectHoneyPotAccessKey, string projectHoneyPostDnsSuffix)
        {
            _projectHoneyPotAccessKey = projectHoneyPotAccessKey;
            _projectHoneyPostDnsSuffix = projectHoneyPostDnsSuffix;
        }

        public bool Validate(HttpContextBase httpContext, Comment comment, IAuthor author, ModelStateDictionary modelState)
        {
            string[] splitIP = comment.GetAuthorIP().Split(new[] { '.' });
            string userReversedIP = string.Format("{0}.{1}.{2}.{3}", splitIP[3], splitIP[2], splitIP[1], splitIP[0]);
            string lookupUrl = string.Format("{0}.{1}.{2}", _projectHoneyPotAccessKey, userReversedIP, _projectHoneyPostDnsSuffix);

            bool valid = IsValid(lookupUrl);

            if(!valid)
                modelState.AddModelError("Comment", "Validation of your IP-address with Project Honey Pot (spambot protection) failed.");

            return valid;
        }

        private bool IsValid(string lookupUrl)
        {
            IPAddress[] ips;
            try
            {
                ips = Dns.GetHostAddresses(lookupUrl);
            }
            catch (SocketException)
            {
                return true;
            }

            if (ips.Length < 1)
                return true;

            byte[] responseIP = ips[0].GetAddressBytes();

            //Check if last Project Honey Pot activity was more than 30 days ago 
            if (responseIP[1] > 30)
                return true;

            //Check if the looked up IP is classified as a search engine spider by Project Honey Pot 
            if (responseIP[0] == 0)
                return true;

            //Check if the Project Honey Pot threat level is higher than 10
            if (responseIP[2] > 10)
                return false;

            return true;
        }
    }
}
